<template>
  <Modal
    :visible="visible"
    title="资源交易管理"
    width="1000px"
    :footer="null"
    :destroy-on-close="true"
    @update:visible="(val) => emit('update:visible', val)"
  >
    <div class="trading-manager">
      <!-- 交易配置标签页 -->
      <Tabs v-model:activeKey="activeTab" type="card">
        <!-- 定价策略 -->
        <TabPane key="pricing" tab="定价策略">
          <div class="pricing-config">
            <div class="section-header">
              <h4>基础定价</h4>
              <Button type="primary" size="small" @click="savePricing">
                <IconifyIcon icon="ant-design:save-outlined" />
                保存定价
              </Button>
            </div>

            <Form :model="pricingForm" layout="vertical">
              <Row :gutter="16">
                <Col :span="12">
                  <FormItem label="基础成本" name="costPrice">
                    <InputNumber
                      v-model="pricingForm.costPrice"
                      :min="0"
                      :precision="2"
                      style="width: 100%"
                      placeholder="请输入基础成本"
                    />
                  </FormItem>
                </Col>
                <Col :span="12">
                  <FormItem label="运营成本" name="operationalCost">
                    <InputNumber
                      v-model="pricingForm.operationalCost"
                      :min="0"
                      :precision="2"
                      style="width: 100%"
                      placeholder="请输入运营成本"
                    />
                  </FormItem>
                </Col>
              </Row>

              <Row :gutter="16">
                <Col :span="12">
                  <FormItem label="标准价格" name="standardPrice">
                    <InputNumber
                      v-model="pricingForm.standardPrice"
                      :min="0"
                      :precision="2"
                      style="width: 100%"
                      placeholder="请输入标准价格"
                    />
                  </FormItem>
                </Col>
                <Col :span="12">
                  <FormItem label="优惠价格" name="discountPrice">
                    <InputNumber
                      v-model="pricingForm.discountPrice"
                      :min="0"
                      :precision="2"
                      style="width: 100%"
                      placeholder="请输入优惠价格"
                    />
                  </FormItem>
                </Col>
              </Row>

              <Row :gutter="16">
                <Col :span="12">
                  <FormItem label="月订阅价格" name="monthlyPrice">
                    <InputNumber
                      v-model="pricingForm.monthlyPrice"
                      :min="0"
                      :precision="2"
                      style="width: 100%"
                      placeholder="请输入月订阅价格"
                    />
                  </FormItem>
                </Col>
                <Col :span="12">
                  <FormItem label="年订阅价格" name="yearlyPrice">
                    <InputNumber
                      v-model="pricingForm.yearlyPrice"
                      :min="0"
                      :precision="2"
                      style="width: 100%"
                      placeholder="请输入年订阅价格"
                    />
                  </FormItem>
                </Col>
              </Row>
            </Form>

            <!-- 定价预览 -->
            <div class="pricing-preview">
              <h4>定价预览</h4>
              <Row :gutter="16">
                <Col :span="8">
                  <Card title="成本分析" size="small">
                    <Statistic title="总成本" :value="totalCost" prefix="¥" />
                    <Statistic
                      title="利润率"
                      :value="profitMargin"
                      suffix="%"
                    />
                  </Card>
                </Col>
                <Col :span="8">
                  <Card title="价格对比" size="small">
                    <Statistic
                      title="标准价格"
                      :value="pricingForm.standardPrice"
                      prefix="¥"
                    />
                    <Statistic
                      title="优惠价格"
                      :value="pricingForm.discountPrice"
                      prefix="¥"
                    />
                  </Card>
                </Col>
                <Col :span="8">
                  <Card title="订阅价格" size="small">
                    <Statistic
                      title="月订阅"
                      :value="pricingForm.monthlyPrice"
                      prefix="¥"
                    />
                    <Statistic
                      title="年订阅"
                      :value="pricingForm.yearlyPrice"
                      prefix="¥"
                    />
                  </Card>
                </Col>
              </Row>
            </div>
          </div>
        </TabPane>

        <!-- 交易对象 -->
        <TabPane key="partners" tab="交易对象">
          <div class="partners-config">
            <div class="section-header">
              <h4>合作对象管理</h4>
              <Button type="primary" size="small" @click="showAddPartner">
                <IconifyIcon icon="ant-design:plus-outlined" />
                添加合作对象
              </Button>
            </div>

            <Table
              :columns="partnerColumns"
              :data-source="partners"
              :pagination="false"
              size="small"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'status'">
                  <Tag :color="record.status === 'active' ? 'green' : 'orange'">
                    {{ record.status === 'active' ? '活跃' : '暂停' }}
                  </Tag>
                </template>
                <template v-else-if="column.key === 'actions'">
                  <Button type="link" size="small" @click="editPartner(record)">
                    编辑
                  </Button>
                  <Button
                    type="link"
                    size="small"
                    danger
                    @click="removePartner(record.id)"
                  >
                    删除
                  </Button>
                </template>
              </template>
            </Table>
          </div>
        </TabPane>

        <!-- 交易规则 -->
        <TabPane key="rules" tab="交易规则">
          <div class="rules-config">
            <div class="section-header">
              <h4>交易规则配置</h4>
              <Button type="primary" size="small" @click="showAddRule">
                <IconifyIcon icon="ant-design:plus-outlined" />
                添加规则
              </Button>
            </div>

            <div class="rules-list">
              <div
                v-for="rule in tradingRules"
                :key="rule.id"
                class="rule-item"
              >
                <div class="rule-header">
                  <IconifyIcon :icon="getRuleTypeIcon(rule.type)" />
                  <span class="rule-name">{{ rule.name }}</span>
                  <Tag :color="rule.status === 'active' ? 'green' : 'orange'">
                    {{ rule.status === 'active' ? '启用' : '禁用' }}
                  </Tag>
                </div>
                <div class="rule-content">
                  <p>{{ rule.description }}</p>
                  <div class="rule-conditions">
                    <strong>条件：</strong>
                    <span
                      v-for="condition in rule.conditions"
                      :key="condition.id"
                    >
                      {{ condition.field }} {{ condition.operator }}
                      {{ condition.value }}
                    </span>
                  </div>
                </div>
                <div class="rule-actions">
                  <Button type="link" size="small" @click="editRule(rule)">
                    编辑
                  </Button>
                  <Button type="link" size="small" @click="toggleRule(rule.id)">
                    {{ rule.status === 'active' ? '禁用' : '启用' }}
                  </Button>
                  <Button
                    type="link"
                    size="small"
                    danger
                    @click="removeRule(rule.id)"
                  >
                    删除
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </TabPane>

        <!-- 交易历史 -->
        <TabPane key="history" tab="交易历史">
          <div class="history-config">
            <div class="section-header">
              <h4>交易记录</h4>
              <div class="header-actions">
                <DatePicker
                  v-model="dateRange"
                  type="daterange"
                  placeholder="选择日期范围"
                  style="width: 200px; margin-right: 8px"
                />
                <Button type="primary" size="small" @click="exportHistory">
                  <IconifyIcon icon="ant-design:download-outlined" />
                  导出记录
                </Button>
              </div>
            </div>

            <Table
              :columns="historyColumns"
              :data-source="filteredHistory"
              :pagination="{ pageSize: 10 }"
              size="small"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'type'">
                  <Tag :color="getTransactionTypeColor(record.type)">
                    {{ record.type }}
                  </Tag>
                </template>
                <template v-else-if="column.key === 'amount'">
                  <span class="amount">¥{{ record.amount }}</span>
                </template>
                <template v-else-if="column.key === 'status'">
                  <Tag :color="getTransactionStatusColor(record.status)">
                    {{ getTransactionStatusText(record.status) }}
                  </Tag>
                </template>
              </template>
            </Table>
          </div>
        </TabPane>
      </Tabs>
    </div>

    <!-- 添加/编辑合作对象模态框 -->
    <Modal
      v-model:visible="partnerModalVisible"
      :title="isEditPartner ? '编辑合作对象' : '添加合作对象'"
      width="500px"
      @ok="savePartner"
    >
      <Form :model="partnerForm" layout="vertical">
        <FormItem label="对象名称" name="name" required>
          <Input v-model="partnerForm.name" placeholder="请输入合作对象名称" />
        </FormItem>
        <FormItem label="对象类型" name="type" required>
          <Select v-model="partnerForm.type" placeholder="请选择对象类型">
            <SelectOption value="SYSTEM">系统</SelectOption>
            <SelectOption value="SERVICE">服务</SelectOption>
            <SelectOption value="CLIENT">客户</SelectOption>
            <SelectOption value="SUPPLIER">供应商</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="状态" name="status">
          <Select v-model="partnerForm.status">
            <SelectOption value="active">活跃</SelectOption>
            <SelectOption value="inactive">暂停</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="描述" name="description">
          <Textarea
            v-model="partnerForm.description"
            placeholder="请输入描述"
          />
        </FormItem>
      </Form>
    </Modal>

    <!-- 添加/编辑交易规则模态框 -->
    <Modal
      v-model:visible="ruleModalVisible"
      :title="isEditRule ? '编辑交易规则' : '添加交易规则'"
      width="600px"
      @ok="saveRule"
    >
      <Form :model="ruleForm" layout="vertical">
        <FormItem label="规则名称" name="name" required>
          <Input v-model="ruleForm.name" placeholder="请输入规则名称" />
        </FormItem>
        <FormItem label="规则类型" name="type" required>
          <Select v-model="ruleForm.type" placeholder="请选择规则类型">
            <SelectOption value="PRICING">定价规则</SelectOption>
            <SelectOption value="DISCOUNT">折扣规则</SelectOption>
            <SelectOption value="VALIDATION">验证规则</SelectOption>
            <SelectOption value="NOTIFICATION">通知规则</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="规则描述" name="description">
          <Textarea
            v-model="ruleForm.description"
            placeholder="请输入规则描述"
          />
        </FormItem>
        <FormItem label="状态" name="status">
          <Select v-model="ruleForm.status">
            <SelectOption value="active">启用</SelectOption>
            <SelectOption value="inactive">禁用</SelectOption>
          </Select>
        </FormItem>
      </Form>
    </Modal>
  </Modal>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch } from 'vue';
import {
  Modal,
  Tabs,
  TabPane,
  Button,
  Form,
  FormItem,
  Input,
  InputNumber,
  Select,
  SelectOption,
  Textarea,
  Table,
  Tag,
  Card,
  Statistic,
  Row,
  Col,
  DatePicker,
  message,
} from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';

// Props
const props = defineProps<{
  visible: boolean;
  resource?: any;
}>();

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean];
  success: [data: any];
}>();

// 响应式数据
const activeTab = ref('pricing');

// 定价配置
const pricingForm = reactive({
  costPrice: 100,
  operationalCost: 50,
  standardPrice: 200,
  discountPrice: 150,
  monthlyPrice: 180,
  yearlyPrice: 1800,
});

// 合作对象
const partners = ref([
  {
    id: 1,
    name: '酒店管理系统',
    type: 'SYSTEM',
    status: 'active',
    description: '核心业务系统',
  },
  {
    id: 2,
    name: '清洁服务团队',
    type: 'SERVICE',
    status: 'active',
    description: '客房清洁服务',
  },
  {
    id: 3,
    name: '客户预订系统',
    type: 'CLIENT',
    status: 'active',
    description: '客户预订平台',
  },
]);

// 交易规则
const tradingRules = ref([
  {
    id: 1,
    name: 'VIP客户折扣',
    type: 'DISCOUNT',
    status: 'active',
    description: 'VIP客户享受9折优惠',
    conditions: [
      { id: 1, field: 'customerLevel', operator: '=', value: 'VIP' },
    ],
  },
  {
    id: 2,
    name: '批量预订优惠',
    type: 'PRICING',
    status: 'active',
    description: '批量预订超过10间享受8折优惠',
    conditions: [{ id: 2, field: 'roomCount', operator: '>=', value: '10' }],
  },
]);

// 交易历史
const tradingHistory = ref([
  {
    id: 1,
    partner: '酒店管理系统',
    type: '订阅',
    amount: 200,
    date: '2024-01-20',
    status: 'completed',
  },
  {
    id: 2,
    partner: '清洁服务团队',
    type: '服务',
    amount: 50,
    date: '2024-01-19',
    status: 'completed',
  },
  {
    id: 3,
    partner: '客户预订系统',
    type: '交易',
    amount: 150,
    date: '2024-01-18',
    status: 'pending',
  },
]);

// 模态框状态
const partnerModalVisible = ref(false);
const ruleModalVisible = ref(false);
const isEditPartner = ref(false);
const isEditRule = ref(false);
const currentPartnerId = ref<number | null>(null);
const currentRuleId = ref<number | null>(null);

// 表单数据
const partnerForm = reactive({
  name: '',
  type: '',
  status: 'active',
  description: '',
});

const ruleForm = reactive({
  name: '',
  type: '',
  status: 'active',
  description: '',
});

// 日期范围
const dateRange = ref<any[]>([]);

// 表格列配置
const partnerColumns = [
  { title: '对象名称', dataIndex: 'name', key: 'name' },
  { title: '对象类型', dataIndex: 'type', key: 'type' },
  { title: '状态', dataIndex: 'status', key: 'status' },
  { title: '描述', dataIndex: 'description', key: 'description' },
  { title: '操作', key: 'actions', width: 120 },
];

const historyColumns = [
  { title: '合作对象', dataIndex: 'partner', key: 'partner' },
  { title: '交易类型', dataIndex: 'type', key: 'type' },
  { title: '金额', dataIndex: 'amount', key: 'amount' },
  { title: '日期', dataIndex: 'date', key: 'date' },
  { title: '状态', dataIndex: 'status', key: 'status' },
];

// 计算属性
const totalCost = computed(() => {
  return pricingForm.costPrice + pricingForm.operationalCost;
});

const profitMargin = computed(() => {
  if (totalCost.value === 0) return 0;
  return (
    ((pricingForm.standardPrice - totalCost.value) /
      pricingForm.standardPrice) *
    100
  ).toFixed(2);
});

const filteredHistory = computed(() => {
  if (!dateRange.value || dateRange.value.length === 0) {
    return tradingHistory.value;
  }
  // 这里可以添加日期过滤逻辑
  return tradingHistory.value;
});

// 方法
const savePricing = () => {
  message.success('定价策略保存成功');
  emit('success', { type: 'pricing', data: pricingForm });
};

const showAddPartner = () => {
  isEditPartner.value = false;
  currentPartnerId.value = null;
  Object.assign(partnerForm, {
    name: '',
    type: '',
    status: 'active',
    description: '',
  });
  partnerModalVisible.value = true;
};

const editPartner = (partner: any) => {
  isEditPartner.value = true;
  currentPartnerId.value = partner.id;
  Object.assign(partnerForm, partner);
  partnerModalVisible.value = true;
};

const savePartner = () => {
  if (isEditPartner.value && currentPartnerId.value) {
    const index = partners.value.findIndex(
      (p) => p.id === currentPartnerId.value,
    );
    if (index > -1) {
      partners.value[index] = { ...partners.value[index], ...partnerForm };
    }
  } else {
    const newPartner = {
      id: Date.now(),
      ...partnerForm,
    };
    partners.value.push(newPartner);
  }

  message.success(
    isEditPartner.value ? '合作对象更新成功' : '合作对象添加成功',
  );
  partnerModalVisible.value = false;
  emit('success', { type: 'partner', data: partners.value });
};

const removePartner = (id: number) => {
  const index = partners.value.findIndex((p) => p.id === id);
  if (index > -1) {
    partners.value.splice(index, 1);
    message.success('合作对象删除成功');
    emit('success', { type: 'partner', data: partners.value });
  }
};

const showAddRule = () => {
  isEditRule.value = false;
  currentRuleId.value = null;
  Object.assign(ruleForm, {
    name: '',
    type: '',
    status: 'active',
    description: '',
  });
  ruleModalVisible.value = true;
};

const editRule = (rule: any) => {
  isEditRule.value = true;
  currentRuleId.value = rule.id;
  Object.assign(ruleForm, rule);
  ruleModalVisible.value = true;
};

const saveRule = () => {
  if (isEditRule.value && currentRuleId.value) {
    const index = tradingRules.value.findIndex(
      (r) => r.id === currentRuleId.value,
    );
    if (index > -1) {
      tradingRules.value[index] = { ...tradingRules.value[index], ...ruleForm };
    }
  } else {
    const newRule = {
      id: Date.now(),
      conditions: [],
      ...ruleForm,
    };
    tradingRules.value.push(newRule);
  }

  message.success(isEditRule.value ? '交易规则更新成功' : '交易规则添加成功');
  ruleModalVisible.value = false;
  emit('success', { type: 'rule', data: tradingRules.value });
};

const toggleRule = (id: number) => {
  const rule = tradingRules.value.find((r) => r.id === id);
  if (rule) {
    rule.status = rule.status === 'active' ? 'inactive' : 'active';
    rule.statusrule.status;
    message.success(`规则${rule.status === 'active' ? '启用' : '禁用'}成功`);
    emit('success', { type: 'rule', data: tradingRules.value });
  }
};

const removeRule = (id: number) => {
  const index = tradingRules.value.findIndex((r) => r.id === id);
  if (index > -1) {
    tradingRules.value.splice(index, 1);
    message.success('交易规则删除成功');
    emit('success', { type: 'rule', data: tradingRules.value });
  }
};

const exportHistory = () => {
  message.success('交易记录导出成功');
};

// 工具方法
const getRuleTypeIcon = (type: string) => {
  const icons: Record<string, string> = {
    PRICING: 'ant-design:dollar-outlined',
    DISCOUNT: 'ant-design:percentage-outlined',
    VALIDATION: 'ant-design:check-circle-outlined',
    NOTIFICATION: 'ant-design:notification-outlined',
  };
  return icons[type] || 'ant-design:setting-outlined';
};

const getTransactionTypeColor = (type: string) => {
  const colors: Record<string, string> = {
    订阅: 'blue',
    服务: 'green',
    交易: 'orange',
  };
  return colors[type] || 'default';
};

const getTransactionStatusColor = (status: string) => {
  const colors: Record<string, string> = {
    completed: 'green',
    pending: 'orange',
    failed: 'red',
  };
  return colors[status] || 'default';
};

const getTransactionStatusText = (status: string) => {
  const texts: Record<string, string> = {
    completed: '已完成',
    pending: '处理中',
    failed: '失败',
  };
  return texts[status] || status;
};

// 初始化数据
const initializeData = () => {
  if (!props.resource?.trading) return;

  try {
    const trading = JSON.parse(props.resource.trading);
    if (trading.pricing) {
      Object.assign(pricingForm, trading.pricing);
    }
    if (trading.partners) {
      partners.value = trading.partners;
    }
    if (trading.rules) {
      tradingRules.value = trading.rules;
    }
    if (trading.history) {
      tradingHistory.value = trading.history;
    }
  } catch (error) {
    console.error('Error initializing trading data:', error);
  }
};

// 监听visible变化
watch(
  () => props.visible,
  (newVisible) => {
    if (newVisible && props.resource) {
      initializeData();
    }
  },
);
</script>

<style lang="less" scoped>
.trading-manager {
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    h4 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
    }

    .header-actions {
      display: flex;
      gap: 8px;
    }
  }

  .pricing-config {
    .pricing-preview {
      margin-top: 24px;
      padding-top: 16px;
      border-top: 1px solid #f0f0f0;
    }
  }

  .partners-config {
    .ant-table {
      margin-top: 16px;
    }
  }

  .rules-config {
    .rules-list {
      .rule-item {
        border: 1px solid #f0f0f0;
        border-radius: 8px;
        padding: 16px;
        margin-bottom: 16px;

        .rule-header {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 8px;

          .rule-name {
            font-weight: 600;
            flex: 1;
          }
        }

        .rule-content {
          margin-bottom: 12px;

          p {
            margin: 0 0 8px 0;
            color: #666;
          }

          .rule-conditions {
            font-size: 12px;
            color: #999;

            span {
              margin-right: 8px;
            }
          }
        }

        .rule-actions {
          display: flex;
          gap: 8px;
        }
      }
    }
  }

  .history-config {
    .ant-table {
      margin-top: 16px;
    }

    .amount {
      font-weight: 600;
      color: #1890ff;
    }
  }
}
</style>
